import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken, getCacheTenant } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import { getCacheRouter } from "@/utils/menu";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

let count = 0;

router.beforeEach(async(to, from, next) => {
  NProgress.start();

  document.title = getPageTitle(to.meta.title);

  const hasToken = getToken();
  // let errorNum = 0;

  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      const tenant = getCacheTenant();
      const routerMenu = getCacheRouter();
      if (tenant && routerMenu) {
        next();
      } else {
        try {
          console.log(count);
          if (count++ <= 5) {
            // 获取租户
            await store.dispatch("tenant/getCurrentTenant");
            // 获取菜单
            await store.dispatch("menu/getLayoutInAuth");
            next();
          } else {
            return;
          }
          if (to.redirectedFrom) {
            // 刷新网页后跳转到刷新前页面
            next(to.redirectedFrom);
          } else {
            next();
          }
        } catch (error) {
          //await store.dispatch('user/resetToken')
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});